package com.lan.iot;

import android.os.Build;
import android.os.Message;

import android.os.Bundle;
import android.telecom.Call;
import android.view.View;
import android.widget.Button;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.lan.iot.entity.AirconditionEntity;
import com.lan.iot.entity.SensorEntity;
import com.lan.iot.utils.JsonUtil;
import com.lan.iot.utils.OkHttpRequestUtil;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.SensorInfo;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.NCallBack;
import cn.com.newland.nle_sdk.util.NetWorkBusiness;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity1 extends AppCompatActivity {


    Button testBtn;

    NetWorkBusiness netWorkBusiness;
    String token;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
         init();
//        testBtn=findViewById(R.id.button);
//        testBtn.setOnClickListener(this);
    }

    private void init() {

       NetWorkBusiness netWorkBusiness2=new NetWorkBusiness("","http://www.nlecloud.com/");
        netWorkBusiness2.signIn(new SignIn("17680316790", "1234567890"), new NCallBack<BaseResponseEntity<User>>(getApplicationContext()) {
            @Override
            protected void onResponse(BaseResponseEntity<User> response) {
                netWorkBusiness=new NetWorkBusiness(response.getResultObj().getAccessToken(),"http://www.nlecloud.com/");
                token=response.getResultObj().getAccessToken();
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case 1:
//               // gainDevices();
//               // delayControl(70); 延迟
//
//                AirconditionEntity airconditionEntity=new AirconditionEntity();
//                airconditionEntity.setTemp("30");
//                airconditionEntity.setModel(1);
//                airconditionEntity.setWindSpeed(1);
//                airconditionEntity.setDeviceID("638233");
//                airconditionEntity.setApiTag("kt1");
//              // airconditionControl(airconditionEntity);
//
//                final String val = JSONObject.toJSONString(airconditionEntity);
//
//
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        test(val);
//                    }
//                }).start();
//
//                break;
//        }
//    }

    /***
     * 控制空调测试函数
     */
    public void cdnControl(){
        AirconditionEntity airconditionEntity=new AirconditionEntity();
        airconditionEntity.setTemp("30");
        airconditionEntity.setModel(1);
        airconditionEntity.setWindSpeed(1);
        airconditionEntity.setDeviceID("638233");
        airconditionEntity.setApiTag("kt1");
        // airconditionControl(airconditionEntity);

        final String val = JSONObject.toJSONString(airconditionEntity);


        new Thread(new Runnable() {
            @Override
            public void run() {

                test(val);
            }
        }).start();
    }

    List<SensorEntity> sensorInfos=new ArrayList<>();
    public List<SensorEntity> gainDevices(){
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        try {
                            //发出网络请求
                            String  NLECLOUD_PROJECT_ID="596248";
                            String  SENSOR_DATA_ALL="http://api.nlecloud.com/Projects/"+NLECLOUD_PROJECT_ID+"/Sensors";

                            Response access = OkHttpRequestUtil.getAccess(SENSOR_DATA_ALL, token);
                            if(access.isSuccessful()){
                                ResponseBody body = access.body();
                                Map map = JsonUtil.toMap(body.string());
                                Double status = (double)map.get("Status");
                                if (status==null||status.intValue()!=0.0)return;//获取失败
                                List<Map<String,Object>> vals= (ArrayList)map.get("ResultObj");
                                sensorInfos.clear();
                                for (Map<String, Object> val : vals) {
                                    SensorEntity sensorInfo=new SensorEntity();
                                    sensorInfo.setApiTag(val.get("ApiTag")+"");
                                    sensorInfo.setName(val.get("Name")+"");
                                    sensorInfo.setDataType((int) (double)val.get("DataType"));
                                    sensorInfo.setValue(val.get("Value")+"");
                                    sensorInfo.setRoomId(checkInRoom(val.get("ApiTag")+""));
                                    sensorInfos.add(sensorInfo);
                                }

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        new Thread(runnable).start();
        return sensorInfos;
    }


    private int checkInRoom(String tag){
        String prefix = tag.substring(0, tag.indexOf("_"));
switch (prefix){
    case "kt":
        return 0;
    case "zw":
        return 1;
    case "cw":
        return 2;
}
        return -1;
    }




    private void airconditionControl(AirconditionEntity entity){
        String s = JSONObject.toJSONString(entity);
        control(entity.getDeviceID(),entity.getApiTag(),JSONObject.toJSONString(entity));
    }
    /**
     *
     * @param tag 设备标签
     * @param val 控制值 0 关闭 1 打开 如果是空调 就直接发送空调的控制 字符串
     */
    public void control(final String deviceID, final String tag, final String val){
    new Thread(new Runnable() {
        @Override
        public void run() {
            netWorkBusiness.control(deviceID, tag, val, new NCallBack<BaseResponseEntity>(getApplicationContext()) {
                @Override
                protected void onResponse(BaseResponseEntity response) {
                    if (response.getStatus()!=0)return;//请求失败

                }
            });
        }
    }).start();
    }



    @RequiresApi(api = Build.VERSION_CODES.O)
    private void delayControl(long minute){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd- hh:mm:ss");
        long currentTime = System.currentTimeMillis();
        Date date=new Date(currentTime);
        String currentTimeVal = format.format(date);
        System.out.println("现在的时间："+currentTimeVal);
        long delayTime=currentTime+minute*60*1000;
        String delayTimeVal = format.format(new Date(delayTime));
        System.out.println("延迟后时间："+delayTimeVal);
    }


private void test(String data){
    //发出网络请求
    String  SENSOR_DATA_ALL="http://api.nlecloud.com/Cmds";
    try {
        Map<String,String> valmap=new HashMap<>();
        valmap.put("deviceId","638233");
        valmap.put("apiTag","kt1");
        Response access =   OkHttpRequestUtil.postAccess(SENSOR_DATA_ALL,valmap,data,token);
        if(access.isSuccessful()){
            ResponseBody body = access.body();
            Map map = JsonUtil.toMap(body.string());
            Double status = (double)map.get("Status");
            if (status==null||status.intValue()!=0.0)return;//获取失败
            List<Map<String,Object>> vals= (ArrayList)map.get("ResultObj");

        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

}

private void test02(){

        netWorkBusiness.getSensor("535963", "kt_temperature", new NCallBack<BaseResponseEntity<SensorInfo>>(getApplicationContext()) {
            @Override
            protected void onResponse(BaseResponseEntity<SensorInfo> response) {
                String value = response.getResultObj().getValue();

                SensorEntity sensorEntity = JSONObject.parseObject(value, SensorEntity.class);
            }
        });

}
}
